<?php

require('config.php');
require('WoWCharacterParser.php');
require('SigGenerator.php');
require('readStats.php');
require('custom_stats.php');

$char = new WoWCharacterParser();
$sig = new SigGenerator();
$statReader = new StatReader();

mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

$stats = array();
$clean = array();

/* zone/region validation */
if (isset($_GET['z']) && $_GET['z'] == 'eu') {
	$clean['zone'] = 'eu';
} else {
	$clean['zone'] = 'us';
}

/* realm name validation */
if (isset($_GET['r'])) {
	if (preg_match("/^[A-Za-z0-9\\\' -]+$/", $_GET['r'])) {
		$realm = ucwords(strtolower($_GET['r']));
		$realm = trim($realm);
		$realm = str_replace('\\\'', '\'', $realm);
		$realm = str_replace(' ', '+', $realm);
		$clean['realm'] = $realm;
	} else {
		$sig->createErrorSig('Invalid realm name');
	}
} else {
	$sig->createErrorSig('Missing realm name');
}

/* char name validation */
//echo 'detection: '.mb_check_encoding($_GET['n'],'UTF-8');
//$result = array();
//mb_parse_str($_GET['n'],$result);
//print_r($result);
//echo 'name:'.$_GET['n'];
if (isset($_GET['n'])) {
	// check data, should be up to 12, ascii chars, auto format to first up
	if (mb_strlen($_GET['n']) <= 12 && preg_match('/^[A-Za-z0-9]{2,16}$/', $_GET['n'])) {
		$clean['name'] = strtoupper(substr($_GET['n'],0,1)).strtolower(substr($_GET['n'],1));
	} else {
		$sig->createErrorSig('Invalid character name');
	}
} else {
	$sig->createErrorSig('Missing character name');
}

/* style validation */
if (isset($_GET['s'])) {
	if (is_numeric($_GET['s']) && $_GET['s'] > 0) {
		$clean['style'] = $_GET['s'];
	} else {
		$sig->createErrorSig('Invalid style');
	}
} else {
	$sig->createErrorSig('Missing style');
}

/* hash validation */
if (isset($_GET['h'])) {
	if (preg_match('/^[0-9a-zA-Z]{5}$/', $_GET['h'])) {
		$clean['hash'] = $_GET['h'];
	} else {
		$sig->createErrorSig('Stats hash failed validation.');
	}
} else {
	// if no hash, set to 'none'
	$clean['hash'] = 'none';
}

// check for cached images, outputs if found
// -- DISABLED, as I now use coral distribution network --
/*if ($sig->imageCache($clean['zone'], $clean['realm'], $clean['name'], 'pve'.$clean['style'], $clean['hash']) == 0) {
	// if there is one, and up to date
	exit;
}*/

// get the data, from cache/blizzard
if ($char->loadData($clean['zone'], $clean['realm'], $clean['name']) > 0) { // failed
	$sig->createErrorSig('Failed to retrieve data. Please try again.');
}

// parse out the XML
$char->parseXML();

$full_profile = true;
// check for error messages here, or for missing data
if (count($char->character['page'][0]['children']['characterinfo'][0]['children']) == 0) {
	// error xml!1!, exit!
	$sig->createErrorSig('An error has occurred. Check spelling.');
} else if (count($char->character['page'][0]['children']['characterinfo'][0]['children']) == 1) {
		// CHAR DATA AWAITING REFRESH!
		// if missing data, we want to write the cache only if no cache exists
	$char->writeCache($clean['zone'], $clean['realm'], $clean['name'], false); 
	// ideally here, we want to refresh more often than if we got real data!?
	$full_profile = false;

} else {
	// plenty of data, overwrite cache!
	$char->writeCache($clean['zone'], $clean['realm'], $clean['name'], true);
	$full_profile = true;
}

$statReader->setCharObject($char);

// the required stats, that we always need to get!
$required = 'ABCDEFGHIJK';

// grab all the required stats first
for ($i = 0; $i < strlen($required); $i++) {
	$stats[$custom_stats[$required[$i]]] = $statReader->getStat($custom_stats[$required[$i]]);
}

if (!$full_profile) {
	$sig->overlayImage('assets/CurllSigBg1.jpg');
	$sig->avatarImage('wow'.(($stats['Level']==70) ? '-70' : (($stats['Level'] < 60) ? '-default' : '')).'/'.$stats['Gender ID'].'-'.$stats['Race ID'].'-'.$stats['Class ID'].'.gif', 1, 1);
	$sig->setFont('assets/fonts/verdanab.ttf');
	$fontsize = 9;
	$sig->writeFont($fontsize, 70, 22, $stats['Name'].' <'.$stats['Guild'].'>', 'white');
	$sig->writeFont($fontsize, 70, 52, $stats['Level'].' '.$stats['Class'], 'white');

	$sig->write(100, 25, 'Character Data Awaiting Refresh', 'yellow');
	$sig->output();
	exit;
}

$hash = '';
if ($clean['hash'] == 'none') {
	$hash = $default_stats[$stats['Class']][$stats['Build']];
} else {
	$hash = $clean['hash'];
}

// loop through the stats that we want to extract and get the data
for ($i = 0; $i < strlen($hash); $i++) {
	$stats[$custom_stats[$hash[$i]]] = $statReader->getStat($custom_stats[$hash[$i]]);
	//echo 'hash'.$i.' : '.$hash[$i].' - '.$custom_stats[$hash[$i]].' - '.$stats[$custom_stats[$hash[$i]]].'<br />';
}

// add it all to the sig
switch ($clean['style']) {
	case 2:
		$sig->overlayImage('assets/pveSigBg2.jpg');
		break;
	case 3:
		$sig->overlayImage('assets/pveSigBg3.jpg');
		break;
	case 4:
		$sig->overlayImage('assets/pveSigBg4.jpg');
		break;
	default:
		$sig->overlayImage('assets/pveSigBg1.jpg');
		break;
}
$sig->avatarImage('wow'.(($stats['Level']==70) ? '-70' : (($stats['Level'] < 60) ? '-default' : '')).'/'.$stats['Gender ID'].'-'.$stats['Race ID'].'-'.$stats['Class ID'].'.gif', 1, 1);
$sig->setFont('assets/fonts/verdanab.ttf');
$fontsize = 9;

//$sig->writeFont($fontsize-2, 70, 10, $title, 'green');

if ($stats['Guild'] != '') {
	$fontguild = $sig->getFontSize($fontsize, 155, 100, '<'.$stats['Guild'].'>');
	$sig->writeFontShadow($fontguild, 70, 35, '<'.$stats['Guild'].'>', 'yellow');
}

$fontname = $sig->getFontSize($fontsize+5, 155, 100, $stats['Name']);
$sig->writeFontShadow($fontname, 70, 22, $stats['Name'], 'white');

$sig->setFont('assets/fonts/verdana.ttf');
$sig->writeFontShadow($fontsize-1, 70, 49, 'LEVEL '.$stats['Level'].' '.strtoupper($stats['Class']), 'white');
$sig->writeFontShadow($fontsize-1, 70, 60, $stats['Talent Tree One'].'/'.$stats['Talent Tree Two'].'/'.$stats['Talent Tree Three'].', '.$stats['Build'], 'white');

$sig->setFont('assets/fonts/verdanab.ttf');
for ($i = 0; $i < strlen($hash); $i++) {
	// gotta handle the special cases! (dynamic titles)
	switch ($custom_stats[$hash[$i]]) {
		case 'Secondbar':
			$sig->writeStats($statReader->getStat('Secondbar Type'), $stats[$custom_stats[$hash[$i]]], 'white');
			break;
		case 'Prof1 Skill':
			$sig->writeStats($statReader->getStat('Prof1 Name'), $stats[$custom_stats[$hash[$i]]], 'white');
			break;
		case 'Prof2 Skill':
			$sig->writeStats($statReader->getStat('Prof2 Name'), $stats[$custom_stats[$hash[$i]]], 'white');
			break;
		case 'Mana Regen2':
			$sig->writeStats('Mana Regen', $stats[$custom_stats[$hash[$i]]], 'white');
		case '<empty>':
			// do nothing!
			break;
		default:
			$sig->writeStats($custom_stats[$hash[$i]], $stats[$custom_stats[$hash[$i]]], 'white');
	}
}

// store the sig in image cache
// -- DISABLED, as I now use coral distribution network --
/*$sig->writeCache($clean['zone'], $clean['realm'], $clean['name'], 'pve'.$clean['style'], $clean['hash']);
*/

// output
$sig->output();
exit;

?>
